<template>
  <div>
    <div
      v-for="item in albums"
      @click="toAlbumMsg(item.id)"
      class="each-album"
      :key="item.id"
    >
      <div class="each-album-pic">
        <img v-lazy="item.blurPicUrl" alt="" />
      </div>
      <div class="each-album-msg">
        <h3>
          {{ item.name }}
        </h3>
        <p>
          {{ item.artists && item.artists[0] && item.artists[0].name }}
        </p>
      </div>
    </div>
    <mu-infinite-scroll
      :loadingText="loadingText"
      :loading="loading"
      @load="fetchData"
    />
  </div>
</template>

<script lang="ts">
import { APIType } from "@/api";
import { Album } from "@/model/music-info.model";
import { SearchType } from "@/model/search-response.model";
import { Vue, Component, Watch } from "vue-property-decorator";
import Router, { Route } from "vue-router";
import _ from "lodash";
import { CommonIdType } from "@/model/id-or-enum.model";
@Component({})
export default class SearchResultAlbumComponent extends Vue {
  albums: Album[] = [];
  loading = false;
  loadingText = "努力加载中...";

  $api: APIType;
  $route: Route;
  $router: Router;

  mounted() {
    this.fetchData();
  }
  get query() {
    return this.$route.query.val;
  }
  @Watch("query")
  private onQueryChange(value: string, prev: string) {
    this.albums = [];
    this.fetchData();
  }
  toAlbumMsg(id: CommonIdType) {
    this.$router.push({ path: `/album/${id}` }).catch((err) => err);
  }
  fetchData() {
    this.loading = true;
    const offset = this.albums.length;
    this.$api
      .searchByType<"Album">(this.$route.query.val, SearchType.Album, offset)
      .then((res) => {
        if (res?.result?.albums?.length) {
          this.albums = [...this.albums, ...res.result.albums];
        }
      })
      .finally(() => {
        this.loading = false;
      });
  }
}
</script>

<style lang="scss" scoped>
.each-album {
  display: flex;
  .each-album-pic {
    width: 1rem;
    height: 1rem;
    padding: 0.1rem;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .each-album-msg {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    border-bottom: 1px solid #f9fafc;
    > h3 {
      font-size: 0.2rem;
      font-weight: 400;
    }
    > p {
      font-size: 0.12rem;
      color: #999;
    }
  }
}
</style>
